package com.kitty.http;

import java.io.*;
import java.net.*;

public class ServerTest {

	 
	public static void main(String[] args) throws IOException {
		ServerSocket ss = new ServerSocket(8080);
		
		while (true) {
			Socket s = ss.accept();
			System.out.println("a new connection.");
			
			Thread t = new Thread(new RequestProcessor(s));
			t.start();
			
		}
	}
	private static class RequestProcessor implements  Runnable{

		private Socket socket;
		private RequestProcessor(Socket socket) {
			this.socket = socket;
			try {
				this.socket.setSoTimeout(1000 * 5);
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		public void run() {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = socket.getInputStream();
				out = socket.getOutputStream();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String string = null;
			try {
				while ((string = reader.readLine()) != null) {
					System.out.println(string);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			String statusLine = "HTTP/1.0 200 OK" + "\r\n";
			String contentTypeLine = "Content-type: text/html\r\n";
			String contentLength = "Content-Length: 23330" + "\r\n";
			String entityBody = "&lt;HTML&gt;"
					+ "&lt;HEAD&gt;&lt;TITLE&gt;404 Not Found&lt;/TITLE&gt;&lt;/HEAD&gt;"
					+ "&lt;BODY&gt;404 Not Found"
					+ "&lt;br&gt;usage:http://yourHostName:port/"
					+ "fileName.html&lt;/BODY&gt;&lt;/HTML&gt;";
			try {
				out.write(statusLine.getBytes());
				out.write(contentTypeLine.getBytes());
				out.write(contentLength.getBytes());
				//out.write("error".getBytes());
				out.write("\r\n".getBytes());
				out.write(entityBody.getBytes());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				out.flush();
				out.close();
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
}

